package com.mlz.mlzmall.ui.activity.act.order;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.CartConfirm;
import com.mlz.mlzmall.bean.DefaultAddressInfo;
import com.mlz.mlzmall.ui.activity.act.address.postCodeToPCD;
import com.mlz.mlzmall.ui.activity.act.base.NetworkActivity;
import com.mlz.mlzmall.ui.activity.act.main.MainActivity;
import com.mlz.mlzmall.ui.activity.act.personal.ReceiveAddress;
import com.mlz.mlzmall.ui.adapter.ConfirmOrderAdapter;
import com.mlz.mlzmall.ui.inter.NetResponses;
import com.mlz.mlzmall.ui.model.StringTools;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.DialogView;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.ListViewUtils;
import com.mlz.mlzmall.volley.util.JsonUtils;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by jack.wang on 2015/11/12.
 */
public class ConfirmOrderActivity extends NetworkActivity implements NetResponses {
    // ListView
    ListView m_lvConfirmOrder;
    // item布局
    int m_nRes;
    boolean isFirst = true;
    private Map map = new HashMap();

    DefaultAddressInfo addressData;
    CartConfirm.Data ccData;
    ConfirmOrderAdapter adapter;

    // 实付款
    TextView m_tvRealTotalPay;
    // 仓库名称
    String m_strWarehouse, couponCode;
    // 姓名
    String RealName = "";
    // 身份证号
    String IdCard = null;
    RelativeLayout RelativeLAddressConfirmOrder;
    // 收货人姓名
    TextView tVReceiverNameConfirmOrder;
    // 默认地址标记
    TextView tvDefaultAddressConfirmOrder;
    // 联系方式
    TextView tvPhoneAddressConfirmOrder;
    // 详细地址
    TextView tvDetailAddressConfirmOrder;

    LinearLayout LLinerLayoutAddressTitle;
    //  实名认证布局
    LinearLayout LLayoutIdCardVerify;
    //  账单布局
    LinearLayout LLinerLayoutBill;
    TextView tvProductTotalMoney;
    TextView tvFreight;
    boolean isNameVerify = false;

    // 税率布局
    TextView TaxTotal;
    // 订单关税总额布局
    LinearLayout LLayoutOrderTotal;
    // 优惠码显示
    TextView PromoCode;
    String realName, sessionKey;
    // 实名验证按钮
    EditText etRealNameConfirm;
    EditText etIdCardConfirm;
    DecimalFormat df = new DecimalFormat("0.00 ");//使价格后保留两位小数
    private int ADD_ADDRESS = 3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.confirm_order_activity);
        setNetResponses(this);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ccData = new CartConfirm.Data();
        // 窗口获得传过来的参数
        m_strWarehouse = getIntent().getStringExtra("warehouse");
        // 初始化控件
        initView();
        // 已经验证的身份证 则隐藏布局

    }

    @Override
    protected void onStart() {
        super.onStart();
        sessionKey = sessionId;
        System.out.println("sessionkey===" + sessionKey);
        getVerifyInfo();
        // 加载数据
        loadData(m_strWarehouse);
    }

    LinearLayout LLayoutRealName;
    LinearLayout LLayoutIdCard;
    RelativeLayout LLayoutDescription;
    TextView tvPassedVerify;

    private void initView() {
        m_lvConfirmOrder = (ListView) findViewById(R.id.listViewConfirmOrder);
        m_tvRealTotalPay = (TextView) findViewById(R.id.realPayTotal);
        m_nRes = R.layout.confirm_order_item;
        //  实名认证 布局
        LLayoutIdCardVerify = (LinearLayout) findViewById(R.id.LLayoutIdCardVerify);
        //  账单布局
        LLinerLayoutBill = (LinearLayout) findViewById(R.id.LLinerLayoutBill);
        // 税率布局
        TaxTotal = (TextView) findViewById(R.id.TaxTotalConfirmOrder);
        // 订单关税总额布局
        LLayoutOrderTotal = (LinearLayout) findViewById(R.id.LLayoutOrderTotal);
        tvFreight = (TextView) findViewById(R.id.tvFreight);
        tvProductTotalMoney = (TextView) findViewById(R.id.tvProductTotalMoneyConfOrder);
        // 实名验证布局
        etRealNameConfirm = (EditText) findViewById(R.id.etRealNameConfirm);
        etIdCardConfirm = (EditText) findViewById(R.id.etIdCardConfirm);
        LLayoutRealName = (LinearLayout) findViewById(R.id.LLayoutRealName);
        LLayoutIdCard = (LinearLayout) findViewById(R.id.LLayoutIdCard);
        LLayoutDescription = (RelativeLayout) findViewById(R.id.LLayoutDescription);
        tvPassedVerify = (TextView) findViewById(R.id.tvPassedVerify);
        // 显示优惠券
        PromoCode = (TextView) findViewById(R.id.PromoCode);
//          详细地址布局
        RelativeLAddressConfirmOrder = (RelativeLayout) findViewById(R.id.RelativeLAddressConfirmOrder);
        RelativeLAddressConfirmOrder.setOnClickListener(this);
        //  收货人姓名
        tVReceiverNameConfirmOrder = (TextView) findViewById(R.id.tVReceiverNameConfirmOrder);
        // 默认地址标记
        tvDefaultAddressConfirmOrder = (TextView) findViewById(R.id.tvDefaultAddressConfirmOrder);
//         联系方式
        tvPhoneAddressConfirmOrder = (TextView) findViewById(R.id.tvPhoneAddressConfirmOrder);
//         详细地址
        tvDetailAddressConfirmOrder = (TextView) findViewById(R.id.tvDetailAddressConfirmOrder);

        LLinerLayoutAddressTitle = (LinearLayout) findViewById(R.id.LLinerLayoutAddressTitle);
        LLinerLayoutAddressTitle.setOnClickListener(this);
    }

    private void popWindow() {

        // 1. 布局文件转换为View对象
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.coupon_dialog, null);
        // 获取view对象里的Edit
        final EditText et = (EditText) layout.findViewById(R.id.etInputPreferentialCode);
        // 2. 新建对话框对象
        final Dialog dialog = new AlertDialog.Builder(ConfirmOrderActivity.this).create();
        dialog.setCancelable(false);
        // 显示对话框 并显示view对象
        dialog.show();
        dialog.getWindow().setContentView(layout);
        // 获取焦点，可以输入字符
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        // 4. 兑换按钮
        TextView tvExchangeDialog = (TextView) layout.findViewById(R.id.tvExchangeDialog);
        tvExchangeDialog.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 兑换优惠券
                if (null != et && !"".equals(et.getText().toString())) {
                    couponCode = et.getText().toString();
                    exchangeCoupon(m_strWarehouse, et.getText().toString());
                }

                dialog.dismiss();
            }
        });
        // 5. 取消按钮
        TextView btnCancel = (TextView) layout.findViewById(R.id.tvCancelDialog);
        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.LLinerLayoutAddressTitle:
            case R.id.RelativeLAddressConfirmOrder:
                Intent intentAdd = new Intent(ConfirmOrderActivity.this, ReceiveAddress.class);
                // 窗口跳转业务类型：添加修改地址
                intentAdd.putExtra("addressAdd", ADD_ADDRESS);
                //仓库名称
                intentAdd.putExtra("warehouse", m_strWarehouse);
                intentAdd.putExtra(ConfigInfo.ACT_STATUS, "1003");

                startActivityForResult(intentAdd, 200);
                overridePendingTransition(R.anim.in_from_right_back_center, R.anim.out_to_left_back_center);
                break;
            case R.id.iv_c_order_back:
                finish();
                overridePendingTransition(R.anim.left_in, R.anim.left_out);
                break;
            case R.id.LinerLayoutCoupons:
                //  弹出框：使用优惠券
                popWindow();
                break;
            case R.id.bt_realNameV:
                // 1:先获取实名认证信息，已认证则隐藏布局,
                // 2: 没认证-->去认证
                realNameVerify();
                break;
            case R.id.reCommitOrder:
                if (null == addressData.getData()) {
                    DialogView dialogView = new DialogView(ConfirmOrderActivity.this, R.layout.dialogview_one, R.style.pager_dialog, 1, "您还没有添加收货地址！");
                    dialogView.show();
                    return;
                } else if (!isNameVerify) {
                    DialogView dialogView = new DialogView(ConfirmOrderActivity.this, R.layout.dialogview_one, R.style.pager_dialog, 1, "您还没有通过实名验证！");
                    dialogView.show();
                    return;
                } else if (!RealName.equals(realName)) {
                    ResultPopWindow(RealName);
                    return;
                }
                checkOut(m_strWarehouse);
                break;
        }
    }


    private void loadData(final String warehouse) {
        request(Request.Method.GET, URL.CART.PREPARE_ORDER + "?warehouse=" + warehouse, null, sessionKey, tag, 300);
    }

    private void getVerifyInfo() {
        request(Request.Method.GET, URL.REALNAME.INFO, null, sessionKey, tag, 100);
    }

    // 兑换优惠券
    public void exchangeCoupon(String warehouse, String couponCode) {
        map.clear();
        map.put("warehouse", warehouse);
        map.put("coupon", couponCode);
        request(Request.Method.POST, URL.CART.SET_COUPON, map, sessionKey, tag, 205);
    }

    public void ResultPopWindow(final String realname) {

        int[] a = {R.id.tv_real_name};
        String[] s = new String[1];
        if (!realname.equals("") || realname != null) {
            s[0] = realname;
        } else {
            s[0] = "HELLO";
        }

        final DialogView dialogView = new DialogView(ConfirmOrderActivity.this, R.layout.dialog_check_name, R.style.pager_dialog, 4, a, s);

        dialogView.setOnBtnClickListener(new DialogView.OnBtnClickListener() {
            @Override
            public void onclick(int i) {
                if (i == 0) {
                    map.clear();
                    map.put("fullname", realname);
                    map.put("addressId", addressData.getData().getAddressId());
                    map.put("address", addressData.getData().getAddress());
                    map.put("shippingTelephone", addressData.getData().getShippingTelephone());
                    map.put("regionCode", addressData.getData().getRegionCode());
                    map.put("postcode", addressData.getData().getPostcode());
                    map.put("defaultAddress", true);
                    request(Request.Method.POST, URL.ADDRESS.EDIT, map, sessionKey, tag, 105);

                } else {
                    dialogView.cancel();
                }
            }
        });
        dialogView.show();
    }

    // 实名验证
    public void saveRealNameVerify(final String realName, final String idCard) {
        Map map = new HashMap();
        map.put("name", realName);
        map.put("certificateCode", idCard);
        request(Request.Method.POST, URL.REALNAME.SAVE, map, sessionKey, tag, 200);
    }

    // 生成订单
    public void checkOut(final String warehouse) {
        map.clear();
        map.put("warehouse", warehouse);
        map.put("comment", "");
        map.put("paymentMethod", "");
        map.put("shippingMethod", "");
        map.put("tracking", "");
        map.put("confirmAddressName", true);
        request(Request.Method.POST, URL.CART.CREATE_ORDER, map, sessionKey, tag, 109);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == 100) {
            loadData(data.getStringExtra("warehouse"));

        }
    }

    // 获取实名信息
    private void realNameVerify() {
        // 获取真实姓名
        EditText etRealNameConfirm = (EditText) findViewById(R.id.etRealNameConfirm);
        // 获取身份证号码
        EditText etIdCardConfirm = (EditText) findViewById(R.id.etIdCardConfirm);
        // 实名验证
        if (etRealNameConfirm.getText().toString().isEmpty() || etIdCardConfirm.getText().toString().isEmpty()) {
            Toast.makeText(getApplicationContext(), "姓名或身份证号码不能为空", Toast.LENGTH_SHORT).show();
        } else if (!etRealNameConfirm.getText().toString().isEmpty() && !etIdCardConfirm.getText().toString().isEmpty()) {
            RealName = etRealNameConfirm.getText().toString();
            saveRealNameVerify(etRealNameConfirm.getText().toString().trim(), etIdCardConfirm.getText().toString().trim());
        }

    }

    @Override
    public void success(int type, JSONObject jsonObject) {

        int status = jsonObject.optInt("status");
        switch (type) {
            case 100:

                JSONObject data = jsonObject.optJSONObject("data");
                if (data != null) {
                    RealName = data.optString("name");
                    LLayoutRealName.setVisibility(View.GONE);
                    LLayoutIdCard.setVisibility(View.GONE);
                    LLayoutDescription.setVisibility(View.GONE);
                    tvPassedVerify.setVisibility(View.VISIBLE);
                    isNameVerify = true;
                } else {
                    LLayoutRealName.setVisibility(View.VISIBLE);
                    LLayoutIdCard.setVisibility(View.VISIBLE);
                    LLayoutDescription.setVisibility(View.VISIBLE);
                    tvPassedVerify.setVisibility(View.GONE);
                    isNameVerify = false;
                }
                break;
            case 105:
                if (status == 0) {
                    tVReceiverNameConfirmOrder.setText(RealName);
                    realName = RealName;
                } else {
                    RealName = "";
                }
                break;
            case 109:
                if (status == 0) {
                    JSONObject object = jsonObject.optJSONObject("data");
                    Intent intent = new Intent(ConfirmOrderActivity.this, OrderPayment.class);
                    startActivity(intent.putExtra("orderCode", object.optString("orderCode")));
//                    if (StringTools.ffff == 100) {
//                        sendBroadcast(new Intent("deleteselectitem"));
//                        StringTools.ffff = 10;
//                    }
                    finish();
                }
                break;
            case 200:
                if (0 == status) {
                    LLayoutRealName.setVisibility(View.GONE);
                    LLayoutIdCard.setVisibility(View.GONE);
                    LLayoutDescription.setVisibility(View.GONE);
                    tvPassedVerify.setVisibility(View.VISIBLE);
                    isNameVerify = true;
                } else {
                    RealName = "";
                    isNameVerify = false;
                    Toast.makeText(ConfirmOrderActivity.this, jsonObject.optString("msg"), Toast.LENGTH_LONG).show();
                }
                break;
            case 205:
                if (status == 0) {
                    loadData(m_strWarehouse);
                    adapter.notifyDataSetChanged();
                    PromoCode.setText("优惠码[" + couponCode + "]");
                } else {
                    Toast.makeText(ConfirmOrderActivity.this, jsonObject.optString("msg"), Toast.LENGTH_LONG).show();
                }
                break;
            case 209:
                if (status == 0) {
                    addressData = JsonUtils.object(jsonObject.toString(), DefaultAddressInfo.class);
                    if (null == addressData.getData()) {
                        //显示添加地址标题栏
                        LLinerLayoutAddressTitle.setVisibility(View.VISIBLE);
                        // 隐藏地址布局
                        RelativeLAddressConfirmOrder.setVisibility(View.GONE);
                    } else if (null != addressData.getData()) {
                        // 显示地址布局
                        RelativeLAddressConfirmOrder.setVisibility(View.VISIBLE);
                        LLinerLayoutAddressTitle.setVisibility(View.GONE);
                        // 收货人姓名
                        tVReceiverNameConfirmOrder.setText(addressData.getData().getFullname());
                        realName = addressData.getData().getFullname();
                        // 默认地址标记
                        if (addressData.getData().isDefaultAddress()) {
                            tvDefaultAddressConfirmOrder.setVisibility(View.VISIBLE);
                        } else {
                            tvDefaultAddressConfirmOrder.setVisibility(View.GONE);
                        }
                        // 联系方式
                        tvPhoneAddressConfirmOrder.setText(addressData.getData().getShippingTelephone());
                        // 获取省 市 区-详细地址
                        StringBuffer sb = new StringBuffer();
                        String RegionCode = String.valueOf(addressData.getData().getRegionCode());
                        postCodeToPCD pcd = new postCodeToPCD(this);
                        sb.append(pcd.province(String.valueOf(RegionCode)));
                        sb.append(pcd.city(String.valueOf(RegionCode)));
                        sb.append(pcd.district(String.valueOf(RegionCode)));
                        sb.append(addressData.getData().getAddress());
                        // 详细地址
                        tvDetailAddressConfirmOrder.setText(sb.toString());
                    }
                }
                break;
            case 300:
                CartConfirm CartConfirm = JsonUtils.object(jsonObject.toString(), com.mlz.mlzmall.bean.CartConfirm.class);
                if (CartConfirm.getStatus() == 0) {
                    ccData = CartConfirm.getData();
                    if (isFirst) {
                        isFirst = false;
                        adapter = new ConfirmOrderAdapter(getBaseContext(), m_nRes, ccData);
                    }
                    m_lvConfirmOrder.setAdapter(adapter);
                    ListViewUtils.setListViewHeightBasedOnChildren(m_lvConfirmOrder, false);

                    if (0 == ccData.getProducts().size()) {
                        LLinerLayoutBill.setVisibility(View.GONE);
                        LLayoutOrderTotal.setVisibility(View.GONE);
                        LLayoutIdCardVerify.setVisibility(View.GONE);
                    }
                    tvProductTotalMoney.setText(String.valueOf(df.format(ccData.getTotals().getSub_total().getValue())));
                    TaxTotal.setText(String.valueOf(df.format(ccData.getTax())));
                    tvFreight.setText(String.valueOf(df.format(ccData.getFreight())));
                    // 实付款
                    m_tvRealTotalPay.setText(String.valueOf(ccData.getTotal()));
                    int addressId = CartConfirm.getData().getAddressId();
                    request(Request.Method.GET, URL.ADDRESS.DETAIL + "?addressId=" + addressId, null, sessionKey, tag, 209);
                } else {
                    showToast(CartConfirm.getMsg());
                }
                break;
        }
    }

    @Override
    public void fail() {

    }


}
